package nachos.vm;

import nachos.machine.*;
import nachos.threads.*;
import nachos.userprog.*;
import nachos.vm.*;

/**
 * A kernel that can support multiple demand-paging user processes.
 */
public class VMKernel extends UserKernel {
    /**
     * Allocate a new VM kernel.
     */
    public VMKernel() {
		super();
    }

    /**
     * Initialize this kernel.
     */
    public void initialize(String[] args) {
		super.initialize(args);

		swap = new Swap();
		pageTable = new PageTable();
    }

    /**
     * Test this kernel.
     */	
    public void selfTest() {
		super.selfTest();

		int pid = 42;
		int vpn = 3;

		long owner = PageTable.makeOwner(pid, vpn);
		System.out.println("pid: " + PageTable.getPid(owner) + " vpn: " + PageTable.getVpn(owner) + " owner: " + owner);

		Lib.assertTrue(pid == PageTable.getPid(owner));
		Lib.assertTrue(vpn == PageTable.getVpn(owner));

    }

    /**
     * Start running user programs.
     */
    public void run() {
	super.run();
    }
    
    /**
     * Terminate this kernel. Never returns.
     */
    public void terminate() {
    	// Close and delete the swapFile
    	swap.swapFile.close();
    	
    	// Display page fault counter
    	System.out.println("Num page faults = " + pageFaultCount);
    	
    	super.terminate();
    }
 
	public Swap swap = null;
	public PageTable pageTable = null;
	protected static Processor processor = Machine.processor();
	public int pageFaultCount = 0;

    // dummy variables to make javac smarter
    private static VMProcess dummy1 = null;

    private static final char dbgVM = 'v';
}
